﻿namespace Security.Authorizations
{
    using System;
    using System.Web;
    using System.Web.UI;
    using System.Security.Principal;
    using System.Web.Hosting;
    using System.Diagnostics;

    internal class Utility
    {
        public static void SendAccessDeniedHeader(Exception ex)
        {
            HttpContext current = HttpContext.Current;
            if (current == null)
            {
                throw ex;
            }

            Send401(current.Response);
        }

        internal static void Send401(HttpResponse response)
        {
            SendResponse(response, 0x191, "401 UNAUTHORIZED");
        }

        internal static void Send403(HttpResponse response)
        {
            SendResponse(response, 0x193, "403 FORBIDDEN");
        }

        //internal static void Send404(HttpRequest request, HttpResponse response)
        //{
        //    SPStringCallback pDataCallback = new SPStringCallback();
        //    string bstrRequestUrl = request.Url.ToString();
        //    string strBody = "404 FILE NOT FOUND";
        //    try
        //    {
        //        SPFarm.RequestNoAuth.RenderErrorPage(0x194, bstrRequestUrl, pDataCallback);
        //        strBody = pDataCallback.StringResult;
        //    }
        //    catch (Exception)
        //    {
        //    }
        //    SendResponse(response, 0x194, strBody);
        //}

        internal static void Send500(HttpResponse response)
        {
            SendResponse(response, 500, "500 INTERNAL SERVER ERROR");
        }

        internal static void SendResponse(HttpResponse response, int code, string strBody)
        {
            HttpContext current = HttpContext.Current;
            object obj2 = current.Items["ResponseEnded"];
            if ((obj2 == null) || !((bool)obj2))
            {
                current.Items["ResponseEnded"] = true;
                response.StatusCode = code;
                response.Clear();
                if (strBody != null)
                {
                    response.Write(strBody);
                }

                response.End();
            }
        }


        internal static bool IsUserAnonymous
        {
            get
            {
                HttpContext current = HttpContext.Current;
                if (current != null)
                {
                    while (current.User.Identity is WindowsIdentity)
                    {
                        var identity = (WindowsIdentity)current.User.Identity;
                        return identity.IsAnonymous;
                    }
                }
                return true;
            }
        }

        //internal static IIdentity CurrentUserIdentity
        //{
        //    [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlPrincipal)]
        //    get
        //    {
        //        if (HttpContext.Current != null)
        //        {
        //            while (!SPSecurity.ImpersonatingSelf)
        //            {
        //                if (HttpContext.Current.User == null)
        //                {
        //                    return new GenericIdentity(string.Empty);
        //                }
        //                return HttpContext.Current.User.Identity;
        //            }
        //        }
        //        return WindowsIdentity.GetCurrent();
        //    }
        //}


        public static string OriginalServerRelativeRequestPath
        {
            get
            {
                HttpContext current = HttpContext.Current;
                if (current != null)
                {
                    return current.Request.Path;
                }
                return null;
            }
        }

        public static string OriginalServerRelativeRequestUrl
        {
            get
            {
                HttpContext current = HttpContext.Current;
                if (current != null)
                {
                    return current.Request.RawUrl;
                }
                return null;
            }
        }
        public static bool IsClientValid(Page page)
        {
            if (page == null)
            {
                throw new ArgumentNullException("page");
            }
            if ((page.Response != null))
            {
                return page.Response.IsClientConnected;
            }
            return true;
        }

        public static void StopRequestIfClientIsNotValid(Page page)
        {
            if (page == null)
            {
                throw new ArgumentNullException("page");
            }
            if (!IsClientValid(page))
            {
                page.Response.End();
            }
        }

        public static string GetDefaultAppName()
        {
            try
            {
                string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath;
                if (string.IsNullOrEmpty(applicationVirtualPath))
                {
                    applicationVirtualPath = Process.GetCurrentProcess().MainModule.ModuleName;
                    int index = applicationVirtualPath.IndexOf('.');
                    if (index != -1)
                    {
                        applicationVirtualPath = applicationVirtualPath.Remove(index);
                    }
                }

                if (string.IsNullOrEmpty(applicationVirtualPath))
                {
                    return "/";
                }
                return applicationVirtualPath;
            }
            catch
            {
                return "/";
            }
        }


        internal static SiteMapNode ReturnNodeIfAccessible(SiteMapNode node)
        {
            if ((node != null) && node.IsAccessibleToUser(HttpContext.Current))
            {
                return node;
            }
            return null;
        }

        internal static bool IsAppRelativePath(string path)
        {
            if (path == null)
            {
                return false;
            }
            int length = path.Length;
            if (length == 0)
            {
                return false;
            }
            if (path[0] != '~')
            {
                return false;
            }
            if ((length != 1) && (path[1] != '\\'))
            {
                return (path[1] == '/');
            }
            return true;
        }

        internal static string MakeVirtualPathAppAbsolute(string virtualPath)
        {
            return MakeVirtualPathAppAbsolute(virtualPath, HttpRuntime.AppDomainAppVirtualPath);

        }

        internal static string MakeVirtualPathAppAbsolute(string virtualPath, string applicationPath)
        {
            if ((virtualPath.Length == 1) && (virtualPath[0] == '~'))
            {
                return applicationPath;
            }
            if (((virtualPath.Length >= 2) && (virtualPath[0] == '~')) && ((virtualPath[1] == '/') || (virtualPath[1] == '\\')))
            {
                if (applicationPath.Length > 1)
                {
                    return (applicationPath + virtualPath.Substring(2));
                }
                return ("/" + virtualPath.Substring(2));
            }
            if (!IsRooted(virtualPath))
            {
                throw new ArgumentOutOfRangeException("virtualPath");
            }
            return virtualPath;
        }

        internal static bool IsRooted(string basepath)
        {
            if (!string.IsNullOrEmpty(basepath) && (basepath[0] != '/'))
            {
                return (basepath[0] == '\\');
            }
            return true;
        }



        //private static void RedirectToAccessDeniedPage(HttpContext context)
        //{
        //    HttpRequest request = context.Request;
        //    SPSite site = SPControl.GetContextWeb(context).Site;
        //    SPObjectType web = SPObjectType.Web;
        //    string keyOrValueToEncode = null;
        //    if (context.Items["CatchAccessDeniedType"] != null)
        //    {
        //        web = (SPObjectType)context.Items["CatchAccessDeniedType"];
        //    }
        //    if (context.Items["CatchAccessDeniedName"] != null)
        //    {
        //        keyOrValueToEncode = (string)context.Items["CatchAccessDeniedName"];
        //    }
        //    string url = "AccessDenied.aspx";
        //    if (request.HttpMethod == "GET")
        //    {
        //        url = url + "?Source=" + SPHttpUtility.UrlKeyValueEncode(site.MakeFullUrl(request.RawUrl));
        //        if (web != SPObjectType.Web)
        //        {
        //            url = url + "&Type=list&name=" + SPHttpUtility.UrlKeyValueEncode(keyOrValueToEncode);
        //        }
        //    }
        //    ULSCat categoryID = ULSCat.msoulscat_WSS_General;
        //    if (ULS.ShouldTrace(categoryID, ULSTraceLevel.Verbose))
        //    {
        //        string str3 = StackTraceString(1);
        //        ULS.SendTraceTag(ULSTagID.tag_8gs1, ULSCat.msoulscat_WSS_General, ULSTraceLevel.Verbose, "Access Denied for %s. StackTrace: %s", new object[] { request.RawUrl, str3 });
        //    }
        //    Redirect(url, SPRedirectFlags.RelativeToLayoutsPage, context);
        //}




        //[DirectoryServicesPermission(SecurityAction.Assert, Unrestricted = true)]
        //internal static bool GetUserInfoFromAD(SPWebApplication webApplicaiton, string loginName, string userAccountDirectoryPath, out string email, out string title, out string jobTitle, out string department, out string sip)
        //{
        //    bool flag = false;
        //    email = null;
        //    title = null;
        //    jobTitle = null;
        //    department = null;
        //    sip = null;
        //    byte[] sidFromAccountName = SPSecurity.GetSidFromAccountName(loginName);
        //    SPActiveDirectoryDomain gcPath = null;
        //    int index = loginName.IndexOf('\\');
        //    if (index > 0)
        //    {
        //        string domainName = loginName.Substring(0, index);
        //        gcPath = SPUserUtility.GetDomainControllerToSearch(webApplicaiton, domainName);
        //    }
        //    if (gcPath != null)
        //    {
        //        ResultPropertyCollection props = PeopleEditor.GetUserPropCollectionBySID(gcPath, sidFromAccountName, ResolveUserAdProperties);
        //        if (props != null)
        //        {
        //            if (!SPUserUtility.DoesUserMeetDirectoryPathRestriction(props, userAccountDirectoryPath, true, webApplicaiton))
        //            {
        //                return flag;
        //            }
        //            flag = true;
        //            email = SPLDAP.GetStringProp(props, ActiveDirectorySchema.Email);
        //            title = SPLDAP.GetStringProp(props, ActiveDirectorySchema.DisplayName);
        //            jobTitle = SPLDAP.GetStringProp(props, ActiveDirectorySchema.JobTitle);
        //            department = SPLDAP.GetStringProp(props, ActiveDirectorySchema.Department);
        //            sip = SPLDAP.GetStringPropInProxyAddress(props, ActiveDirectorySchema.Sip);
        //            if (!string.IsNullOrEmpty(title))
        //            {
        //                return flag;
        //            }
        //            title = loginName;
        //        }
        //        return flag;
        //    }
        //    flag = true;
        //    email = string.Empty;
        //    title = loginName;
        //    jobTitle = string.Empty;
        //    sip = string.Empty;
        //    return flag;
        //}




    }
}